<!-- 排班设置页 -->
<template>
  <div class="dashboard-container waybill-list customer-list-box">
    <el-card class="box-card">
      <!-- 添加按钮 -->
      <div class="button-group">
        <el-button
          type="warning"
          @click="addwork"
        >添加工作模式</el-button>
      </div>

      <!-- 列表 -->
      <el-table
        :data="tableData"
        style="width: 100%"
      >
        <el-table-column
          prop="id"
          label="工作模式编号"
          width="280"
        >
        </el-table-column>
        <el-table-column
          prop="name"
          label="工作模式"
          width="280"
        >
        </el-table-column>
        <el-table-column
          prop="workPatternTypeDesc"
          width="280"
          label="类型"
        >
        </el-table-column>
        <el-table-column
          prop="workDate"
          label="工作日期"
          width="280"
        >
        </el-table-column>
        <el-table-column
          prop="workEndHour"
          width="380"
          label="工作时间"
        >
          <template #default="scope">
            {{ workTime(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="操作"
        >
          <template #default="scope">
            <el-button
              type="text"
              @click="redact(scope.row.id)"
            >编辑</el-button>
            <el-button
              type="text"
              style="color: red"
              @click="removework(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页功能 -->
      <div class="paging">
        <el-pagination
          :current-page="params.page"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="params.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </el-card>
    <!-- 新增弹框 -->
    <el-dialog
      title="新增工作模式"
      :visible.sync="dialogVisible"
      width="30%"
      @close="handleClose"
    >
      <span>
        <el-tabs
          v-model="workPatternType"
          @tab-click="handleClick"
        >
          <el-tab-pane
            v-if="!isEdit || workPatternType === '1'"
            label="礼拜制"
            name="1"
          >
            <!-- 输入框 -->
            <el-form
              ref="ruleForm"
              :model="addForm"
              :rules="rules"
              label-width="100px"
              class="demo-ruleForm"
            >
              <el-form-item
                label="活动名称"
                prop="name"
              >
                <el-input v-model="addForm.name" />
              </el-form-item>
              <!-- 复选框 -->
              <el-form-item
                label="连续工作天数："
                placeholder="请填写工作模式名称"
                prop="monday"
                class="week-group"
              >
                <div class="week-list">
                  <el-checkbox v-model="addForm.monday">周一</el-checkbox>
                  <el-checkbox v-model="addForm.tuesday">周二</el-checkbox>
                  <el-checkbox v-model="addForm.wednesday">周三</el-checkbox>
                  <el-checkbox v-model="addForm.thursday">周四</el-checkbox>
                  <el-checkbox v-model="addForm.friday">周五</el-checkbox>
                  <el-checkbox v-model="addForm.saturday">周六</el-checkbox>
                  <el-checkbox v-model="addForm.sunday">周日</el-checkbox>
                </div>
                <div class="week-msg">选中为工作时间，未选中为休息时间</div>
              </el-form-item>
              <el-form-item
                label="工作时间："
                prop="times"
              >
                <el-time-picker
                  v-model="addForm.times"
                  is-range
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  placeholder="选择时间范围"
                  format="HH:mm"
                  value-format="HH:mm"
                  @change="setWeekTime"
                >
                </el-time-picker>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane
            v-if="!isEdit || workPatternType === '2'"
            label="连续制"
            name="2"
          >
            <el-form
              key="addworkFrom"
              ref="addworkFrom"
              :rules="sustainRules"
              :model="addworkFrom"
              label-width="120px"
              class="demo-form-inline"
            >
              <el-form-item
                label="工作模式名称："
                prop="name"
              >
                <el-input
                  v-model="addworkFrom.name"
                  placeholder="请填写工作模式名称"
                />
              </el-form-item>

              <el-form-item
                label="连续工作天数："
                class="time-group"
                prop="workDayNum"
              >
                <el-input
                  v-model="addworkFrom.workDayNum"
                  placeholder="请输入"
                >
                  <template slot="prepend">上</template>
                  <template slot="append">天</template>
                </el-input>

                <el-input
                  v-model="addworkFrom.restDayNum"
                  placeholder="请输入"
                >
                  <template slot="prepend">休</template>
                  <template slot="append">天</template>
                </el-input>
              </el-form-item>

              <el-form-item
                label="工作时间："
                prop="times"
              >
                <el-time-picker
                  v-model="addworkFrom.times"
                  is-range
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  placeholder="选择时间范围"
                  format="HH:mm"
                  value-format="HH:mm"
                  @change="setSustainTime"
                >
                </el-time-picker>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </span>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="addsumbit"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { workHistoryList, addWorkHistory, workHistoryInfo, updateWorkHistory, deleteWorkHistory } from '@/api/transit'
export default {
  data () {
    return {
      tableData: [],
      params: {
        page: 1,
        pageSize: 10
      },
      total: null,
      dialogVisible: false, // 弹框开关
      addForm: {
        friday: false,
        monday: false,
        name: '',
        saturday: false,
        sunday: false,
        thursday: false,
        tuesday: false,
        wednesday: false,
        workEndMinutel: null,
        workStartMinutel: null,
        times: ['08:00', '20:00']
      },
      addworkFrom: {
        name: '',
        restDayNum: '',
        workDayNum: '',
        workEndMinutel: null,
        workStartMinutel: null,
        times: ['08:00', '20:00']
      },
      rules: {
        name: [{ required: true, message: '工作模式不能为空', trigger: 'blur' }]
      },
      sustainRules: {},
      workPatternType: '1',
      isEdit: false,
      parosid: null
    }
  },
  created () {
    this.getTableList()
  },
  methods: {
    // 获取页面列表数据
    async getTableList () {
      const res = await workHistoryList(this.params)
      // console.log(res)
      this.tableData = res.data.items
      this.total = +res.data.counts
    },
    // 计算时间
    workTime (val) {
      // console.log(val)
      return (
        ((val.workEndMinute1 - val.workStartMinute1) / 60).toFixed(2) + '小时'
      )
    },
    // 页面大小改变时触发的事件
    handleSizeChange (val) {
      this.params.pageSize = val
      this.getTableList()
    },
    // 页面跳转触发的事件
    handleCurrentChange (val) {
      this.params.page = val
      this.getTableList()
    },
    // 新增弹框按钮
    addwork () {
      this.dialogVisible = true
      this.isEdit = false
    },
    // 弹窗关闭
    handleClose () {
      this.dialogVisible = false
      this.addForm = {
        friday: false,
        monday: false,
        name: '',
        saturday: false,
        sunday: false,
        thursday: false,
        tuesday: false,
        wednesday: false,
        workEndMinutel: null,
        workStartMinutel: null,
        times: ['08:00', '20:00']
      }
      this.addworkFrom = {
        name: '',
        restDayNum: '',
        workDayNum: '',
        workEndMinutel: null,
        workStartMinutel: null,
        times: ['08:00', '20:00']
      }
    },
    // 时间事件
    setWeekTime () {
      console.log(this.addForm.times)
      const [hour, minute] = this.addForm.times[0].split(':')
      this.addForm.workStartMinute1 = parseInt(hour) * 60 + parseInt(minute)
      // console.log(this.addForm.workStartMinute1)
      const [hour1, minute1] = this.addForm.times[1].split(':')
      this.addForm.workEndMinute1 = parseInt(hour1) * 60 + parseInt(minute1)
    },
    filterDate (times) {
      // console.log(this.addForm.times)
      const [hour, minute] = times[0].split(':')
      const startTime = parseInt(hour) * 60 + parseInt(minute)
      // console.log(this.addForm.workStartMinute1)
      const [hour1, minute1] = times[1].split(':')
      const endTime = parseInt(hour1) * 60 + parseInt(minute1)
      return [startTime, endTime]
    },
    // 导航栏切换事件
    handleClick () {},
    setSustainTime () {},
    // 新增请求处理日期的方法
    filterWeek (val) {
      return val ? '1' : '2'
    },
    // 处理新增或编辑数据
    filterQueryData () {
      let queryData = {}
      if (this.workPatternType - 1) {
        const { name, restDayNum, workDayNum, times } = this.addworkFrom
        const [workEndMinutel, workStartMinutel] = this.filterDate(times)
        queryData = {
          name,
          restDayNum,
          workDayNum,
          workEndMinutel,
          workStartMinutel
        }
      } else {
        const {
          friday,
          monday,
          name,
          saturday,
          sunday,
          thursday,
          tuesday,
          wednesday,
          workEndMinutel,
          workStartMinutel
        } = this.addForm
        queryData = {
          name,
          workEndMinutel,
          workStartMinutel,
          friday: this.filterWeek(friday),
          monday: this.filterWeek(monday),
          saturday: this.filterWeek(saturday),
          sunday: this.filterWeek(sunday),
          thursday: this.filterWeek(thursday),
          tuesday: this.filterWeek(tuesday),
          wednesday: this.filterWeek(wednesday)
        }
      }
      queryData.workPatternType = this.workPatternType
      if (this.isEdit) {
        queryData.id = this.parosid
      }
      return queryData
    },
    // 编辑时间星期数据处理
    filterEditWeek (val) {
      if (val === 1) {
        return true
      } else {
        return false
      }
    },
    // 编辑时间数据处理
    timeIn (val) {
      console.log(val)
      const hours = Math.floor(val / 60)
      const minutes = val % 60
      const timeStr = `${String(hours).padStart(2, '0')}:${String(
        minutes
      ).padStart(2, '0')}`
      return timeStr
    },
    // 点击弹框确认按钮
    async addsumbit () {
      try {
        if (this.workPatternType - 1) {
          await this.$refs.addworkFrom.validate()
        } else {
          await this.$refs.ruleForm.validate()
        }
      } catch (error) {
        this.$message.error('*为必填项')
        return
      }
      const queryData = this.filterQueryData()

      // 判断添加或修改
      try {
        if (this.isEdit) {
          // 修改逻辑
          await updateWorkHistory(queryData)
        } else {
          // 添加逻辑
          await addWorkHistory(queryData)
        }
        this.$message.success(this.isEdit ? '编辑成功' : '新增成功')
        this.getTableList()
        this.handleClose()
      } catch (error) {
        this.$message.error('失败')
      }
    },
    // 编辑按钮数据回显
    async redact (id) {
      // console.log(id)
      this.parosid = id
      this.isEdit = true
      this.dialogVisible = true
      const res = await workHistoryInfo(id)
      console.log(res.data)
      const {
        friday,
        monday,
        name,
        saturday,
        sunday,
        thursday,
        tuesday,
        wednesday,
        workStartMinute1,
        workEndMinute1,
        restDayNum,
        workDayNum,
        workPatternType
      } = res.data
      if (workPatternType === 1) {
        this.workPatternType = '1'
        this.addForm = {
          friday: this.filterEditWeek(friday),
          monday: this.filterEditWeek(monday),
          name: name,
          saturday: this.filterEditWeek(saturday),
          sunday: this.filterEditWeek(sunday),
          thursday: this.filterEditWeek(thursday),
          tuesday: this.filterEditWeek(tuesday),
          wednesday: this.filterEditWeek(wednesday),
          times: [this.timeIn(workStartMinute1), this.timeIn(workEndMinute1)]
        }
      } else if (workPatternType === 2) {
        this.workPatternType = '2'
        this.addworkFrom = {
          name: name,
          restDayNum: restDayNum,
          workDayNum: workDayNum,
          times: [this.timeIn(workStartMinute1), this.timeIn(workEndMinute1)]
        }
      }
    },
    // 删除功能
    async removework(id) {
      this.$confirm('此操作将永久删除该设置, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await deleteWorkHistory(id)
          this.$message.success(`删除成功`)
          this.getTableList()
        } catch (error) {
          this.$message.error(`删除失败`)
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep  .table-card-box {
  .el-card__body {
    padding-bottom: 0px;
  }
}
::v-deep  .pagination {
  padding-bottom: 30px;
}
.tab-box {
  color: #20232a;
  ::v-deep .el-tabs__item.is-active {
    color: #20232a;
    font-size: 16px;
    font-weight: bold;
  }
  ::v-deep  .el-form-item__content {
    height: 40px;
  }
  ::v-deep .el-tabs__item {
    font-size: 14px;
  }
  ::v-deep  .el-tabs__item:hover {
    color: #20232a;
    font-size: 16px;
    font-weight: bold;
    cursor: pointer;
  }
  ::v-deep  .el-tabs__active-bar {
    background-color: #e15536;
  }
  ::v-deep  .tips {
    margin-left: 130px;
    margin-bottom: 14px;
    color: #bac0cd;
  }
  .el-checkbox {
    margin-right: 5px;
  }
  ::v-deep  .workDay {
    .el-form-item__error {
      position: relative;
    }
  }
}
::v-deep  .el-dialog__body {
  padding-top: 30px !important;
  .el-tabs__header {
    padding-bottom: 25px;
  }
}
::v-deep  .el-tabs__nav,
.is-top {
  transform: translateX(30px) !important;
}
.box-card {
  margin: 20px;
  padding: 10px;
  //新增按钮
  .button-group {
    margin-bottom: 20px;
    .el-button {
      width: 118px;
      text-align: center;
    }
  }
  .paging {
    margin-top: 20px;
    ::v-deep .el-pagination {
      text-align: center;
    }
  }
}
::v-deep .el-dialog {
  .el-dialog__body {
    padding: 10px 20px;
    .add-continer {
      margin: 0 40px;
      .el-tabs {
        .el-tabs__header.is-top {
          padding: 0;
          margin: 0;
          .el-tabs__item.is-top.is-active,
          .el-tabs__item.is-top:hover {
            font-size: 16px;
            font-weight: 700;
            color: #20232a;
          }
          .el-tabs__active-bar.is-top {
            background-color: #f56c6c;
          }
        }
      }
      .el-form {
        margin-top: 20px;
        .el-form-item {
          margin-bottom: 20px;
          .week-list {
            width: 100%;
            display: flex;
            justify-content: space-between;
            padding-right: 10px;
            .el-checkbox {
              margin: 0;
            }
          }
          .week-msg {
            height: 30px;
            line-height: 30px;
          }
          &.time-group {
            .el-form-item__content {
              display: flex;
              .el-input {
                width: 45%;
                .el-input-group__prepend,
                .el-input-group__append {
                  background-color: #fff;
                }
                &:first-child {
                  margin-right: 10%;
                }
              }
            }
          }
        }
      }
    }
  }
  .el-dialog__footer {
    display: flex;
    align-items: center;
    justify-content: center;
    padding-bottom: 40px;
    .el-button {
      margin-left: 20px;
      span {
        padding: 0 10px;
      }
    }
  }
}
.el-checkbox {
  margin-right: 5px;
}
::v-deep .el-form-item__label {
  font-size: 12px;
}
.el-input {
  width: 45%;
  .el-input-group__prepend,
  .el-input-group__append {
    background-color: #fff;
  }
}
</style>
